/*
 * Copyright (C) 2024-2025 Deepin Technology Co., Ltd.
 *
 * Author:     zhangbingyi <zhangbingyi@uniontech.com>
 *
 * Maintainer: zhangbingyi <zhangbingyi@uniontech.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "datausagewidget.h"
#include "datausagemodel.h"
#include "speedwidget.h"
#include "appdatadetaildialog.h"
#include "common/systemsettings.h"
#include "gsettingkey.h"
#include "invokers/invokerfactory.h"
#include "widgets/hframe1.h"

#include <QListView>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QDebug>
#include <QComboBox>
#include <QTableView>
#include <QHeaderView>
#include <functional>
#include <QToolButton>
#include <QMenu>


DataUsageWidget::DataUsageWidget(DataUsageModel *model, QWidget *parent)
    : QFrame(parent)
    , m_model(model)
    , m_speedwidget(nullptr)
    , m_flowwidget(nullptr)
    , m_layout(new QVBoxLayout)
    , m_widget(new QWidget(this))
    , m_topSwitchWidgetBtn(new QDialogButtonBox)
    , m_tablelayout(new QVBoxLayout)
    , m_sysSettings(new SystemSettings(this))
    , m_monitorInterFaceServer(nullptr)
{
    this->setAccessibleName("rightWidget_dataUsageWidget");
    m_topSwitchWidgetBtn->setAccessibleName("dataUsageWidget_switchButton");

    m_monitorInterFaceServer = InvokerFactory::GetInstance().CreateInvoker("com.deepin.defender.MonitorNetFlow",
                                                                           "/com/deepin/defender/MonitorNetFlow",
                                                                           "com.deepin.defender.MonitorNetFlow",
                                                                           ConnectType::SYSTEM, this);

    initUI();

    // 系统配置改变
    connect(m_sysSettings, SIGNAL(valueChanged(const QString &, const QVariant &)), this, SLOT(onSysSettingChanged(const QString &, const QVariant &)));
}

DataUsageWidget::~DataUsageWidget()
{
}

void DataUsageWidget::slotChangeControlStatus(bool isChecked)
{
    Q_UNUSED(isChecked)
    // 状态取反
    bool on = !m_sysSettings->getValue(DATA_USAGE_ON_OFF).toBool();
    DBUS_NOBLOCK_INVOKE(m_monitorInterFaceServer, "EnableNetFlowMonitor", on);

    // 添加安全日志
    if (on) {
        DBUS_NOBLOCK_INVOKE(m_monitorInterFaceServer, "AddSecurityLog", SECURITY_LOG_TYPE_TOOL, tr("Data usage: ON"));
    } else {
        DBUS_NOBLOCK_INVOKE(m_monitorInterFaceServer, "AddSecurityLog", SECURITY_LOG_TYPE_TOOL, tr("Data usage: OFF"));
    }
}

void DataUsageWidget::onSysSettingChanged(const QString &key, const QVariant &value)
{
    // 如果流量监控开关状态改变
    if (DATA_USAGE_ON_OFF == key) {
        m_dataSwitchButton->setChecked(value.toBool());
    }
}

void DataUsageWidget::onButtonClicked(QAbstractButton *btn)
{
    if (btnUpdate == btn)
        settype(static_cast<TabelType>(0));
    else if (btnSetting == btn)
        settype(static_cast<TabelType>(1));
}

//初始化ui界面
void DataUsageWidget::initUI()
{
    installEventFilter(this);
    //将　widget　加入到一个新建的　DBackgroundGroup中
    QVBoxLayout *bglayout = new QVBoxLayout;
    bglayout->setContentsMargins(0, 0, 0, 0);
//    m_bgGroup = new DBackgroundGroup(bglayout, this);
//    m_bgGroup->setBackgroundRole(QPalette::Window);
    bglayout->addWidget(m_widget);

    //将 m_bgGroup 沉底
//    m_bgGroup->lower();

    //设置m_bgGroup 的大小
//    m_bgGroup->setFixedSize(size());

    //控制按钮
    QHBoxLayout *controlLayout = new QHBoxLayout;
    controlLayout->setContentsMargins(10, 0, 10, 0);
    controlLayout->setSpacing(0);
    QLabel *dataLabel = new QLabel(tr("Data usage"), this);
    dataLabel->setAccessibleName("usageFrame_usageLabel");
    QFont font1 = dataLabel->font();
    dataLabel->setFont(font1);
//    DFontSizeManager::instance()->bind(dataLabel, DFontSizeManager::T5);

    m_dataSwitchButton = new HSwitchButton;
    m_dataSwitchButton->setFixedSize(60, 30);
    m_dataSwitchButton->setAccessibleName("usageFrame_usageButton");
    m_dataSwitchButton->setChecked(m_sysSettings->getValue(DATA_USAGE_ON_OFF).toBool());
    connect(m_dataSwitchButton, SIGNAL(statusChanged(bool)), this, SLOT(slotChangeControlStatus(bool)));

    controlLayout->addWidget(dataLabel);
    controlLayout->addWidget(m_dataSwitchButton);

    HFrame1 *titleFrame = new HFrame1;
    titleFrame->setAccessibleName("dataUsageWidget_usageFrame");
    titleFrame->setBackgroundType(HFrame1::Normal);
    titleFrame->setFixedSize(730, 46);
    titleFrame->setLayout(controlLayout);

    //按钮item
    btnUpdate = m_topSwitchWidgetBtn->addButton(tr("Apps and Services"), QDialogButtonBox::NoRole);
    btnUpdate->setAccessibleName("switchButton_currentButton");
    btnSetting = m_topSwitchWidgetBtn->addButton(tr("Rankings"), QDialogButtonBox::NoRole);
    btnSetting->setAccessibleName("switchButton_rankingsButton");
    btnUpdate->setFixedWidth(160);
    btnSetting->setFixedWidth(160);
    refreshElideText(btnUpdate, tr("Apps and Services"));
    refreshElideText(btnSetting, tr("Rankings"));

    m_topSwitchWidgetBtn->setMaximumSize(320, 36);
    m_topSwitchWidgetBtn->setMinimumSize(320, 36);

    connect(m_topSwitchWidgetBtn, SIGNAL(clicked(QAbstractButton*)), this, SLOT(onButtonClicked(QAbstractButton*)));

    m_layout->setMargin(0);
    m_layout->setAlignment(Qt::AlignTop);
    m_layout->addWidget(titleFrame);
    m_layout->addSpacing(10);
    m_layout->addWidget(m_topSwitchWidgetBtn, 0, Qt::AlignHCenter);

    setLayout(m_layout);

    m_layout->addLayout(m_tablelayout);

    showAppsServices();
}

//根据按钮显示对应界面
void DataUsageWidget::settype(TabelType type)
{
    m_tabeltype = type;
    switch (type) {
    case AppsServices:
        showAppsServices();
        break;
    case Trafficranking:
        showTrafficranking();
        break;
    }
}

void DataUsageWidget::refreshElideText(QPushButton *pBtn, const QString& strText)
{
    QFontMetrics fontmet(pBtn->font());
    QString elidedStr = fontmet.elidedText(strText, Qt::TextElideMode::ElideMiddle, pBtn->width() - 10);
    pBtn->setText(elidedStr);
    if (fontmet.width(strText) > pBtn->width() - 10) {
        pBtn->setToolTip(strText);
    } else {
        pBtn->setToolTip("");
    }
}

//网速界面
void DataUsageWidget::showAppsServices()
{
    if (m_flowwidget != nullptr) {
        m_flowwidget->hide();
        m_tablelayout->removeWidget(m_flowwidget);
        disconnect(m_flowwidget);
        m_flowwidget->deleteLater();
        m_flowwidget = nullptr;
    }

    if (nullptr == m_speedwidget) {
        m_speedwidget = new SpeedWidget(m_model, this);
        m_speedwidget->setContentsMargins(0, 0, 0, 0);
        m_tablelayout->addWidget(m_speedwidget);
        m_speedwidget->show();
    }
}

//流量界面
void DataUsageWidget::showTrafficranking()
{
    if (m_speedwidget != nullptr) {
        m_speedwidget->hide();
        m_tablelayout->removeWidget(m_speedwidget);
        disconnect(m_speedwidget);
        m_speedwidget->deleteLater();
        m_speedwidget = nullptr;
    }

    if (nullptr == m_flowwidget) {
        m_flowwidget = new FlowWidget(m_model, this);
        m_flowwidget->setContentsMargins(0, 0, 0, 0);
        m_tablelayout->addWidget(m_flowwidget);
        m_flowwidget->show();
    }
}

//设置背景大小
void DataUsageWidget::resizeEvent(QResizeEvent *event)
{
    QFrame::resizeEvent(event);

    //设置m_bgGroup 的大小
//    if (m_bgGroup)
//        m_bgGroup->setFixedSize(size());
}

bool DataUsageWidget::eventFilter(QObject *obj, QEvent *event)
{
    if (obj == this) {
        // 如果当前是字体改变的事件
        if (event->type() == QEvent::FontChange) {
            refreshElideText(btnUpdate, tr("Apps and Services"));
            refreshElideText(btnSetting, tr("Rankings"));
        }
    }
    return QFrame::eventFilter(obj, event);
}
